package com.mayisoftware.mayioa.business.po.impl.serviceImpl;


import com.mayisoftware.mayioa.business.po.api.domain.POBasicInfo;
import com.mayisoftware.mayioa.business.po.api.domain.POImportInfo;
import com.mayisoftware.mayioa.business.po.api.service.IPOUploadService;
import com.mayisoftware.mayioa.business.po.impl.dao.POUploadMapper;
import com.mayisoftware.mayioa.common.impl.utils.DateUtils;
import com.mayisoftware.mayioa.common.impl.utils.ExcelReadWriteUtils;
import com.mayisoftware.mayioa.platform.api.domain.SysDictData;
import com.mayisoftware.mayioa.platform.api.domain.SysUser;
import com.mayisoftware.mayioa.platform.api.service.ISysDictDataService;
import com.mayisoftware.mayioa.platform.impl.util.ShiroUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class POUploadServiceImpl implements IPOUploadService {

    @Autowired
    private ISysDictDataService dictService;

    @Autowired
    private POUploadMapper importMapper;

    @Override
    public int insertImportOneRecord(POImportInfo wtImportInfo) {
        return importMapper.insertImportOneRecord(wtImportInfo);
    }

    @Override
    public List<POImportInfo> queryRecordList(POImportInfo wtImportInfo) {
        return importMapper.selectRecordList(wtImportInfo);
    }

    @Override
    public List<POImportInfo> queryRecordListById(String recordId) {
        return importMapper.selectRecordListById(recordId);
    }

    @Override
    public List<POImportInfo> queryRecordListNeedParse() {
        return importMapper.selectRecordListNeedParse();
    }

    @Override
    public int editInputRecord(POImportInfo record) {
        return importMapper.updateInputRecord(record);
    }


    @Override
    public boolean check(POImportInfo updateRecord,File uploadFile){

        List<POBasicInfo> poBasicInfos = getPOImportInfos(uploadFile);
        if (poBasicInfos==null || poBasicInfos.size()==0){
            return  false;
        }

        String userName = updateRecord.getUserName();
        for (POBasicInfo poInfo:poBasicInfos) {
            int existCount = importMapper.isPoExist(poInfo);
            if (existCount>0){
                importMapper.deleteExistPo(poInfo);
            }
            poInfo.setUpdateBy(userName);
            importMapper.insertPoInfo(poInfo);
        }
        return true;
    }

    private List<POBasicInfo> getPOImportInfos(File poFile){
        List<POBasicInfo> retList = new ArrayList<>();
        File detailFile = new File(poFile.getAbsolutePath());
        List<String> contents =null;
        try {
            contents= ExcelReadWriteUtils.readExcelList(detailFile.getAbsolutePath(),0);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            return retList;
        } catch (IOException e) {
            e.printStackTrace();
            return retList;
        }

        int count = 0;
        for (String item: contents) {
            count++;
            if (count == 1) {
                continue;
            }

            String tmp = item.replace(",","");
            if (tmp.trim().isEmpty()){
                continue;
            }

            List<String> items = Arrays.asList(item.split(",",-1));
            POBasicInfo poImportInfo = new POBasicInfo();

            poImportInfo.setPrjCreateCode(items.get(0));
            poImportInfo.setPoCode(items.get(1));
            poImportInfo.setPoName(items.get(2));
            poImportInfo.setPrjType(getDictValue("po_type",items.get(3)));
            poImportInfo.setPdu(getDictValue("human_pdu",items.get(4)));
            poImportInfo.setRegion(getDictValue("check_region",items.get(5)));
            poImportInfo.setStatus(getDictValue("po_status",items.get(6)));
            poImportInfo.setHwPM(items.get(7));
            poImportInfo.setIsoftPM(items.get(8));
            poImportInfo.setPoAmounts(Double.parseDouble(items.get(9)));
            poImportInfo.setMonthPeoples(Integer.parseInt(items.get(10)));
            poImportInfo.setStartDate(convertToDateString(items.get(11)));
            poImportInfo.setEndDate(convertToDateString(items.get(12)));
            poImportInfo.setPoConsumedAmounts(Double.parseDouble(items.get(13)));
            poImportInfo.setPoSurplusAmounts(Double.parseDouble(items.get(14)));
            poImportInfo.setPoConsumedRate(Float.parseFloat(items.get(15).replaceAll("%","")));
            poImportInfo.setPoConsumeDate(convertToDateString(items.get(16)));
            poImportInfo.setNewPORisk(getDictValue("risk_level",items.get(17)));
            poImportInfo.setNewPORemark(items.get(18));
            retList.add(poImportInfo);
        }
        return retList;
    }

    private String convertToDateString(String val){
        if (val.contains("-")){
            return val;
        }else if(val.contains("/")){
            return  val.replaceAll("/","-");
        }

        try {
            Long.parseLong(val);
            Date date = DateUtils.covertToDate(DateUtils.YYYY_MM_DD,val);
            return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,date);
        }catch (Exception e){
            return  val;
        }

    }

    public String getDictLabel(String dictType, String dictValue) {
        return  dictService.selectDictLabel(dictType,dictValue);
    }

    public String getDictValue(String dictType, String dictLabel) {
        List<SysDictData> dicts = dictService.selectDictDataByType(dictType);
        for (SysDictData dict:dicts) {
            if (dict.getDictLabel().equalsIgnoreCase(dictLabel)){
                return  dict.getDictValue();
            }
        }
        return "";
    }
}
